// 引入创建路由的关键方法
import { createWebHistory, createRouter } from "vue-router";
// 引入路由配置
import routes from "@/router/routes";
// 进度条
import Nprogress from "nprogress";

import { LoginProduct, UserRightProduct } from "@/api/Product/index";
import { getCookie, getToken, setCookie } from "@/utils/Cookies/Cookies";

import { ElMessage } from "element-plus";
import store from "@/store/store";

const _loginProduct = new LoginProduct();
const _UserRightProduct = new UserRightProduct();
// 创建路由
const router = createRouter({
  history: createWebHistory(),
  routes: routes,
});

// 前置导航
router.beforeEach((to, form, next) => {
  store.state.Active = true;
  Nprogress.start();
  if (to.meta.title) {
    document.title = to.meta.title as string;
  } else {
    document.title = "前端模板";
  }
  if (!to.meta.NotCheck) {
    if (!getToken()) {
      router.push("/");
    }

  if (to.meta.index) {
    _UserRightProduct.AuthenticationUserRights({ url: to.meta.index }).then((res) => {
      if (res.code != 0) {
        router.push("/NoPermissions");
      }
    });
  }

  _loginProduct.CheckLogin().then((res) => {
    if (res) {
       setCookie('UserInfo', JSON.stringify(res.data), 1);
    } else {
      ElMessage.error("你还未登录或者被挤下线");
      router.push("/");
    }
  });
  }


  next();
});
// 后置导航
router.afterEach((to, form, next) => {
  Nprogress.done();
  store.state.Active = false;
});

export default router;
